﻿using System;
using System.Collections.Generic;
using System.Data;
using DevExpress.XtraEditors;
using UniMana.Data;
using UniMana.Utils.Configs;
using UniMana.Utils.Data;
namespace UniMana.Win.Leadership
{
    public partial class FrmReportScoreMajor : DevExpress.XtraEditors.XtraForm
    {
        private DBMain m_data = new DBMain();
        private DataTable m_tblTable = new DataTable();
        private DataTable m_tblReport = new DataTable();
        private List<string> ListStudentKey;
        private int m_iDepartmentKey = 0;

        private List<string> ScoreName;
        private List<double> ScoreModel;
        private List<int> ScoreNumber;

        public DevExpress.Utils.WaitDialogForm dlg;

        public FrmReportScoreMajor()
        {
            InitializeComponent();
            SysUtils.SetRuleControl(this.Controls, this.Name);
            m_iDepartmentKey = Utils.LoginInfo.GblLoginInfo.iDepartmentKey;
        }

        private void FrmReportScoreMajor_Load(object sender, EventArgs e)
        {
            LoadData();
            Initial();
        }

        private void LoadData()
        {
            gluCatalogue_Major.GetData(
                m_data.m_DCReadOnly.Catalogue_Majors.GetListByDepartmentKey(
                m_data.m_DCReadOnly.Catalogue_Levels, 
                m_iDepartmentKey).ToDataTable());
            lueCatalogue_Course.GetData(
                m_data.m_DCReadOnly.Catalogue_Courses.GetCourseKeyNameInTrainingProgram(
                this.m_data.m_DCReadOnly.Training_TrainingPrograms, 
                this.m_data.m_DCReadOnly.Catalogue_Majors));
            lueCatalogue_SchoolYear.GetData(
                m_data.m_DCReadOnly.Catalogue_SchoolYears.GetSchoolYearInTrainingProgram(
                this.m_data.m_DCReadOnly.Training_Subject_Opens));

            lueCatalogue_Course.EditValue = int.Parse(
                m_data.m_DCReadOnly.Catalogue_Courses.GetCourseKeyNameInTrainingProgram(
                this.m_data.m_DCReadOnly.Training_TrainingPrograms,
                this.m_data.m_DCReadOnly.Catalogue_Majors).
                ToDataTable().
                Rows[m_data.m_DCReadOnly.Catalogue_Courses.GetCourseKeyNameInTrainingProgram(
                this.m_data.m_DCReadOnly.Training_TrainingPrograms, 
                this.m_data.m_DCReadOnly.Catalogue_Majors).
                ToDataTable().
                Rows.Count - 1]["Catalogue_CourseKey"].ToString());
        }

        private void Initial()
        {
            try
            {
                m_tblTable.Columns.Clear();
                m_tblReport.Columns.Clear();
                m_tblTable.Rows.Clear();
                m_tblReport.Rows.Clear();
                m_tblReport.Columns.Add("Name");
                m_tblReport.Columns.Add("Number");
                ListStudentKey = new List<string>();

                ScoreName = new List<string>();
                ScoreName.Add(txtType1.Text);
                ScoreName.Add(txtType2.Text);
                ScoreName.Add(txtType3.Text);
                ScoreName.Add(txtType4.Text);
                ScoreName.Add(txtType5.Text);
                ScoreName.Add(txtType6.Text);
                ScoreName.Add(txtType7.Text);

                ScoreModel = new List<double>();
                ScoreModel.Add(Convert.ToDouble(txtScore1.Text));
                ScoreModel.Add(Convert.ToDouble(txtScore2.Text));
                ScoreModel.Add(Convert.ToDouble(txtScore3.Text));
                ScoreModel.Add(Convert.ToDouble(txtScore4.Text));
                ScoreModel.Add(Convert.ToDouble(txtScore5.Text));
                ScoreModel.Add(Convert.ToDouble(txtScore6.Text));

                ScoreNumber = new List<int>();
                ScoreNumber.Add(0);
                ScoreNumber.Add(0);
                ScoreNumber.Add(0);
                ScoreNumber.Add(0);
                ScoreNumber.Add(0);
                ScoreNumber.Add(0);
                ScoreNumber.Add(0);

                gctView.DataSource = m_tblReport;
                cacScore.DataSource = m_tblReport;
                cacScore.Refresh();
            }
            catch { }
        }

        /// <summary>
        /// Kiểm tra thông tin để lấy dữ liệu
        /// </summary>
        /// <returns></returns>

        private int CheckInfo()
        {
            if ((GetValueLookUpEdit.ConvertValueToInt(gluCatalogue_Major.EditValue) > 0) && 
                (GetValueLookUpEdit.ConvertValueToInt(lueCatalogue_Course.EditValue) > 0) && 
                (GetValueLookUpEdit.ConvertValueToInt(lueCatalogue_SchoolYear.EditValue) > 0))
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }

        /// <summary>
        /// Kiểm tra nhập thông tin điểm null
        /// </summary>
        /// <returns></returns>

        private bool CheckScoreNull()
        {
            if ((txtType1.Text != "") && 
                (txtScore1.Text != "") && 
                (txtType2.Text != "") && 
                (txtScore2.Text != "") && 
                (txtType3.Text != "") && 
                (txtScore3.Text != "") && 
                (txtType4.Text != "") && 
                (txtScore4.Text != "") && 
                (txtType5.Text != "") && 
                (txtScore5.Text != "") && 
                (txtType6.Text != "") && 
                (txtScore6.Text != "") && 
                (txtType7.Text != ""))
                return true;
            else
                return false;
        }

        /// <summary>
        /// Kiểm tra nhập điểm
        /// </summary>
        /// <returns></returns>

        private bool CheckInfoScoreList()
        {
            if (!CheckScoreNull())
            {
                return false;
            }
            for (int i = 1; i < 6; i++)
            {
                for (int j = i + 1; j < 7; j++)
                {
                    if (Convert.ToDouble(
                        layoutControl2.Controls["txtScore" + i].Text) < 
                        Convert.ToDouble(layoutControl2.Controls["txtScore" + j].Text))
                    {
                        return false;
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// Lấy danh sách studentKey
        /// </summary>

        private void GetListStudentKey(DataTable m_tblTable)
        {
            try
            {
                DataTable a = new DataTable();
                a = m_tblTable;
                ListStudentKey.Add(a.Rows[0]["Training_StudentKey"].ToString());
                for (int i = 0; i < a.Rows.Count; i++)
                {
                    int _d = 1;
                    for (int j = 0; j < ListStudentKey.Count; j++)
                    {
                        if (a.Rows[i]["Training_StudentKey"].ToString() == ListStudentKey[j].ToString())
                        {
                            _d = 0;
                            break;
                        }
                    }
                    if (_d == 1)
                    {
                        ListStudentKey.Add(a.Rows[i]["Training_StudentKey"].ToString());
                    }
                }
            }
            catch { }
        }

        /// <summary>
        /// Tính điểm
        /// </summary>
        /// <param name="m_strStudentID"></param>
        /// <param name="m_tblTable"></param>
        /// <returns></returns>

        private double ScoringOfStudent(string m_strStudentKey, ref DataTable m_tblTable)
        {
            try
            {
                double m_dScore = 0;
                List<string> listTerm = new List<string>(); // danh sách học kỳ

                DataTable table = new DataTable();
                table.Columns.Add("Training_StudentKey");
                table.Columns.Add("Catalogue_TermKey"); ;
                table.Columns.Add("Score");
                table.Columns.Add("DefaultPercent");
                table.Columns.Add("TotalCredits");

                for (int i = 0; i < m_tblTable.Rows.Count; i++)
                {
                    if (m_tblTable.Rows[i]["Training_StudentKey"].ToString() == m_strStudentKey)
                    {
                        table.Rows.Add(
                            m_tblTable.Rows[i]["Training_StudentKey"], 
                            m_tblTable.Rows[i]["Catalogue_TermKey"], 
                            m_tblTable.Rows[i]["Score"], 
                            m_tblTable.Rows[i]["DefaultPercent"], 
                            m_tblTable.Rows[i]["TotalCredits"]);
                        m_tblTable.Rows.RemoveAt(i);
                        i--;
                    }
                }

                // Lấy danh sách học kỳ của sinh viên
                listTerm.Add(table.Rows[0]["Catalogue_TermKey"].ToString());
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    int _d = 1;
                    for (int j = 0; j < listTerm.Count; j++)
                    {
                        if (listTerm[j].ToString() == table.Rows[i]["Catalogue_TermKey"].ToString())
                        {
                            _d = 0;
                            break;
                        }
                    }
                    if (_d == 1)
                    {
                        listTerm.Add(table.Rows[i]["Catalogue_TermKey"].ToString());
                    }
                }

                // Mảng chứa tổng số tín chỉ và tổng điểm từng học kỳ
                double[,] ScoreTerm = new double[listTerm.Count, 2];
                for (int i = 0; i < listTerm.Count; i++)
                {
                    ScoreTerm[i, 0] = 0;
                    ScoreTerm[i, 1] = 0;
                }

                // Tính điểm theo học kỳ cho sinh viên

                for (int i = 0; i < listTerm.Count; i++)
                {
                    DataTable tableTerm = new DataTable();
                    tableTerm.BeginInit();
                    tableTerm.BeginLoadData();
                    tableTerm.Columns.Add("Training_StudentKey");
                    tableTerm.Columns.Add("Catalogue_TermKey");
                    tableTerm.Columns.Add("Score");
                    tableTerm.Columns.Add("DefaultPercent");
                    tableTerm.Columns.Add("TotalCredits");
                    tableTerm.Columns.Add("average");

                    for (int j = 0; j < table.Rows.Count; j++)
                    {
                        if (table.Rows[j]["Catalogue_TermKey"].ToString() == listTerm[i].ToString())
                        {
                            tableTerm.Rows.Add(
                                table.Rows[j]["Training_StudentKey"], 
                                table.Rows[j]["Catalogue_TermKey"], 
                                table.Rows[j]["Score"], 
                                table.Rows[j]["DefaultPercent"], 
                                table.Rows[j]["TotalCredits"]);
                            table.Rows.RemoveAt(j);
                            j--;
                        }
                    }

                    // Tính điểm trung bình
                    for (int j = 0; j < tableTerm.Rows.Count; j = j + 2)
                    {
                        double _iScore = 0;
                        _iScore = (
                            ((Convert.ToDouble(tableTerm.Rows[j]["Score"].ToString())) * 
                            (Convert.ToDouble(tableTerm.Rows[j]["DefaultPercent"].ToString()))) / 100) + 
                            (((Convert.ToDouble(tableTerm.Rows[j + 1]["Score"].ToString())) * 
                            (Convert.ToDouble(tableTerm.Rows[j + 1]["DefaultPercent"].ToString()))) / 100);
                        tableTerm.Rows[j]["average"] = _iScore.ToString();
                    }
                    // Ghi nhận tổng số tín chỉ cho học kỳ và tổng số điểm của học kỳ
                    for (int j = 0; j < tableTerm.Rows.Count; j = j + 2)
                    {
                        ScoreTerm[i, 0] = 
                            ScoreTerm[i, 0] + 
                            Convert.ToDouble(tableTerm.Rows[j]["TotalCredits"].ToString());
                        ScoreTerm[i, 1] = 
                            ScoreTerm[i, 1] + 
                            Convert.ToDouble(tableTerm.Rows[j]["average"].ToString()) * 
                            Convert.ToDouble(tableTerm.Rows[j]["TotalCredits"].ToString());
                    }
                    tableTerm.EndInit();
                    tableTerm.EndLoadData();
                }

                double _credit = 0;
                double _score = 0;
                // Tính điểm bình quân cho cả năm
                for (int i = 0; i < listTerm.Count; i++)
                {
                    _credit = _credit + ScoreTerm[i, 0];
                    _score = _score + ScoreTerm[i, 1];
                }
                m_dScore = _score / _credit;
                return m_dScore;
            }
            catch { return 0; }
        }

        /// <summary>
        /// Sắp xếp sinh viên theo loại điểm
        /// </summary>

        private void Arrangement(double score)
        {
            try
            {
                int _d = 1;
                for (int i = 0; i < ScoreModel.Count; i++)
                {
                    if (score > ScoreModel[i])
                    {
                        _d = 0;
                        ScoreNumber[i] = ScoreNumber[i] + 1;
                        break;
                    }
                }
                if (_d == 1)
                {
                    ScoreNumber[6] = ScoreNumber[6] + 1;
                }
            }
            catch { }
        }

        /// <summary>
        /// Xem dữ liệu thống kê
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void btnView_Click(object sender, EventArgs e)
        {
            if (CheckInfoScoreList())
            {
                try
                {
                    if (CheckInfo() == 1)
                    {
                        dlg = new DevExpress.Utils.WaitDialogForm(MsgConfig.MSG_WAIT, MsgConfig.MSG_LOADING);
                        Initial();
                        m_tblTable = 
                            (ReportScoreMajor.GetScoreOfStudentByMajorCourseSchoolYear(
                            m_data.m_DCReadOnly.Training_Scores,
                        m_data.m_DCReadOnly.Training_Student_Classes,
                        m_data.m_DCReadOnly.Training_Subject_Classes,
                        m_data.m_DCReadOnly.Training_SubjectClass_ScoreTypes,
                        m_data.m_DCReadOnly.Training_Student_Subjects,
                        GetValueLookUpEdit.ConvertValueToInt(gluCatalogue_Major.EditValue),
                        GetValueLookUpEdit.ConvertValueToInt(lueCatalogue_Course.EditValue),
                        GetValueLookUpEdit.ConvertValueToInt(lueCatalogue_SchoolYear.EditValue))).ToDataTable();

                        if (m_tblTable.Rows.Count != 0)
                        {
                            try
                            {
                                GetListStudentKey(m_tblTable);
                                for (int i = 0; i < ListStudentKey.Count; i++)
                                {
                                    double a = ScoringOfStudent(ListStudentKey[i].ToString(), ref m_tblTable);
                                    Arrangement(a);
                                }
                                for (int i = 0; i < ScoreName.Count; i++)
                                {
                                    m_tblReport.Rows.Add(ScoreName[i].ToString(), ScoreNumber[i]);
                                }
                                gctView.DataSource = m_tblReport;
                                // Phần xuất thống kê

                                cacScore.DataSource = m_tblReport;
                                cacScore.Series[0].ArgumentDataMember = "Name";
                                cacScore.Series[0].TopNOptions.Enabled = true;
                                cacScore.Series[0].ArgumentDataMember = "Name";
                                cacScore.Series[0].Name = "Xếp loại";
                                cacScore.Series[0].TopNOptions.Enabled = true;
                                cacScore.Series[0].ValueDataMembersSerializable = "Number";
                                cacScore.Refresh();
                            }
                            catch
                            {
                                XtraMessageBox.Show("Không thể thống kê với dữ liệu được chọn");
                            }
                        }
                        else
                        {
                            XtraMessageBox.Show("Không có dữ liệu thống kê");
                        }
                    }
                    else
                    {
                        XtraMessageBox.Show("Chưa chọn đủ thông tin");
                    }
                    dlg.Close();
                }
                catch { }
            }
            else
            {
                XtraMessageBox.Show("Danh sách điểm thống kê không đúng qui tắc hoặc nhập thiếu thông tin");
            }
        }

        /// <summary>
        /// Chọn ngành
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void lueCatalogue_Major_Click(object sender, EventArgs e)
        {
            Initial();
        }

        /// <summary>
        /// Chọn khóa học
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void lueCatalogue_Course_Click(object sender, EventArgs e)
        {
            Initial();
        }

        /// <summary>
        /// Chọn năm học
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void lueCatalogue_SchoolYear_Click(object sender, EventArgs e)
        {
            Initial();
        }

        /// <summary>
        /// In
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void btnPrinf_Click(object sender, EventArgs e)
        {
            compositeLink1.ShowPreview();
        }
    }
}
